import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import store from '../../store';
import api from '../../api';
import './style.css'
import line from '../../assets/image/needle.047d988b.png'

class AudioDetail extends Component {
    constructor(props) {
        super(props)
    
        this.state = {
            lyric:[],
            currentTime: 0,
            isPlay:true,
            lyricStatus: false,
            rateList: [0.75, 1.0, 1.25, 1.5, 2.0],
            playRate: 1.0,
            allTime:0
        }
    }
    
    componentDidMount(){
        api.getPublic(`/lyric?id=${store.getState().inputValue.id}`).then(res=>{
            console.log("网络请求歌词", res.data.lrc)
                        if (res.data.lrc) {



                            var str = res.data.lrc.lyric;
                            const lineStrings = str.split('\n');
                            const lyricList = [];
                            const parseExp = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/;
                            for (let line of lineStrings) {
                                if (line) {
                                    const lrcContent = line.replace(parseExp, '').trim();
                                    const timeResult = parseExp.exec(line);
                                    const milliseconds =
                                        timeResult[3].length == 3
                                            ? timeResult[3] * 1
                                            : timeResult[3] * 10;
                                    const lrcTime =
                                        timeResult[1] * 60 * 1000 + timeResult[2] * 1000 + milliseconds;
                                    lyricList.push({
                                        lyc: lrcContent,
                                        time: lrcTime,
                                    });
                                }
                            }
                            console.log('修改后的歌词',lyricList);
                            this.setState({
                                lyric: [...lyricList]
                            })
                        } else {
                            this.setState({
                                lyric: ["该歌曲无歌词"]
                            })
                        }
        })
    }
    // 设置歌词时间
    formatSecond(time) {
        const second = Math.floor(time % 60);
        let minite = Math.floor(time / 60);
        return `${minite}:${second >= 10 ? second : `0${second}`}`;
    }

    // 点击倍速
    changePlayRate = (num) => {
        // this.audioDom.playbackRate = num;
       return() =>{
        this.setState({
            playRate: num,
        });
       }
    };
    // 点击暂停
    pauseAudio = ()=>{
       
        const audio = document.getElementById(`audio${store.getState().music.id}`);
            this.setState({
                isPlay:false
            })
            

            audio.pause();// 这个就是暂停
   
    }
    //点击播放
    playAudio = ()=>{
        const audio = document.getElementById(`audio${store.getState().music.id}`);
            this.setState({
                isPlay:true
            })
            audio.play()
    }


    // 当前播放位置改变时执行
    onTimeUpdate = () => {
        // const { id } = this.props;
        const audio = document.getElementById(`audio${store.getState().music.id}`);

        this.setState({
            currentTime: audio.currentTime,
        });
        if (audio.currentTime === audio.duration) {
            this.setState({
                isPlay: false,
            });
        }
    };



        // 该视频已准备好开始播放
        onCanPlay = () => {
            // const { id } = this.props;
            const audio = document.getElementById(`audio${store.getState().music.id}`);
            this.setState({
                allTime: audio.duration,
            });
    
    
            // this.aga(this.state.currentTime)
    
            // 当前音乐播放完毕监听
            audio.addEventListener("ended", () => {

                if (this.state.currentTime == this.state.allTime) {
                    console.log("音乐播放完毕")
    
                }
            });
    
    
    
    
        };

        // 返回上一个页面
        backSheet = () =>{
            this.props.history.go(-1)
        }

        changeLyricState = () => {
            this.setState({
                lyricStatus: !this.state.lyricStatus
            })
        }
    // 歌词
        agszg = (a, b, c) => {
            // let hahaha = document.getElementById("hahaha")
            // console.log("-a,b,c",a,b,c)
    
            return (b.filter(v => {
                return (v.time - 0 - 1000) <= (c.split(":")[1] * 1000 + c.split(":")[0] * 60 * 1000)
            }
            )[b.filter(v => {
                return (v.time - 0 - 1000) <= (c.split(":")[1] * 1000 + c.split(":")[0] * 60 * 1000)
            }
            ).length - 1]) ? b.filter(v => {
                return (v.time - 0 - 1000) <= (c.split(":")[1] * 1000 + c.split(":")[0] * 60 * 1000)
            }
            ).length - 1 : false
    
        }
        // aleft = () =>{
        //     let index=0;
        //     store.getState().list.map((v,i)=>{
        //         if(v.id===store.getState().music.id){
        //            index = i
        //         }

        //     })
        // }

    render() {
        console.log(store.getState());
        return (
            <div>
                <div className="audio-detail">
                    <div className="audio-header">
                        <div className="audio-header-left" onClick={this.backSheet}><span className="iconfont icon-xiajiantou"></span></div>
                        <div className="audio-header-right">
                            <p className="header-right-top">{ store.getState().inputValue.name}</p>
                            <p className="header-right-bottom">{ store.getState().inputValue.ar[0].name}{store.getState().inputValue.ar[1]?<span>/{store.getState().inputValue.ar[1].name}</span>:null}</p> 
                        </div>
                        
                    </div>
                    <div className="audio-container">
                    <img className={this.state.isPlay ? "audio-container-line audio-container-line-pause" : "audio-container-line"} src={line} alt="" />
                    <div className={this.state.lyricStatus ? 'round-hide' : "round"}  onClick={this.changeLyricState}>
                            <div className="round-img">
                            <img src={store.getState().inputValue.al.picUrl}  alt=""/>
                            </div>
                        </div>
                    
                    </div>
                    <p className={this.state.lyricStatus ? "lyric-hide" : "lyric"}>{(this.state.lyric.filter(v => {
                            return (v.time - 0 - 1000) <= (this.formatSecond(this.state.currentTime).split(":")[1] * 1000 + this.formatSecond(this.state.currentTime).split(":")[0] * 60 * 1000)
                        }
                        )[this.state.lyric.filter(v => {
                            return (v.time - 0 - 1000) <= (this.formatSecond(this.state.currentTime).split(":")[1] * 1000 + this.formatSecond(this.state.currentTime).split(":")[0] * 60 * 1000)
                        }
                        ).length - 1]) ? (this.state.lyric.filter(v => {
                            return (v.time - 0 - 1000) <= (this.formatSecond(this.state.currentTime).split(":")[1] * 1000 + this.formatSecond(this.state.currentTime).split(":")[0] * 60 * 1000)
                        }
                        )[this.state.lyric.filter(v => {
                            return (v.time - 0 - 1000) <= (this.formatSecond(this.state.currentTime).split(":")[1] * 1000 + this.formatSecond(this.state.currentTime).split(":")[0] * 60 * 1000)
                        }
                        ).length - 1]).lyc : ""
                        } </p>


                        <div ref="ps" id="hahaha" onClick={this.changeLyricState} className={this.state.lyricStatus ? "lyric-show" : "round-hide"}>
                            {
                                this.state.lyric.map((v, i) => {
                                    return <p
                                        style={{
                                            color: this.agszg(v, this.state.lyric, this.formatSecond(this.state.currentTime)) == i ? "red" : "white",
                                            transform: this.agszg(v, this.state.lyric, this.formatSecond(this.state.currentTime)) == i ? 'scale(1)'
                                                : 'scale(0.8)'

                                        }}
                                        key={i}
                                        ref=""
                                    >{v.lyc}</p>
                                    // lyc: temp[2], //歌词内容

                                })
                            }
                        </div>
                </div>

                <div className="audio-footer">
                        <div className="audio-footer-rate">
                            <span>倍速播放：</span>
                            {this.state.rateList &&
                                this.state.rateList.length > 0 &&
                                this.state.rateList.map((item) => (
                                    <button
                                        key={item}
                                        style={
                                            this.state.playRate === item
                                                ? {
                                                    border: "1px solid #dd1b24",
                                                    color: "#dd1b24",
                                                }
                                                : null
                                        }
                                        onClick={ this.changePlayRate(item)}
                                    >
                                        X{item}
                                    </button>
                                ))}


                        </div>
                        <div className="audio-footer-progress">


                            <span className="audio-footer-duration">
                                {this.formatSecond(this.state.currentTime)}
                            </span>
                            <div className="audio-footer-line">
                                <input
                                    className="progress"
                                    type="range"
                                    step="0.01"
                                    max={this.state.allTime}
                                    value={this.state.currentTime}
                                    onChange={this.changeTime}
                                    style={{ backgroundSize: '' + (this.state.currentTime / this.state.allTime) * 100 + '%' }}
                                    readOnly
                                />
                            </div>
                            <span className="audio-header-currentTime">
                                {this.formatSecond(this.state.allTime)}
                            </span>

                        </div>
                        <div className="audio-header-icon">
                            <div>
                                <span onClick={() => this.btnab()} id="btnaa" className="iconfont icon-24gl-repeat2"></span>
                            </div>
                            <div>
                                <span onClick={() => this.aleft()} className="iconfont icon-shangyishoushangyige"></span>
                            </div>
                            <div>
                                {this.state.isPlay ? (
                                    <span onClick={this.pauseAudio} className="iconfont icon-bofang1"></span>
                                ) : (
                                        <span onClick={this.playAudio} className="iconfont icon-zanting"></span>
                                    )}
                            </div>
                            <div onClick={() => this.aright()}>
                                <span className="iconfont icon-xiayigexiayishou"></span>
                            </div>
                            <div>
                                <span onClick={this.props.btnabaer} className="iconfont icon-yinleyinpin"></span>

                            </div>
                        </div>
                    </div>

                    <div className="audio-play">


                            <audio
                                id={`audio${store.getState().music.id}`}
                                src={`https://music.163.com/song/media/outer/url?id=${store.getState().music.id}.mp3`}
                                ref={(audio) => {
                                    this.audioDom = audio;
                                }}
                                preload={"auto"}
                                autoPlay
                                onCanPlay={this.onCanPlay}
                                onTimeUpdate={this.onTimeUpdate}
                            >
                                <track src={store.getState().music.url} kind="captions" />
                            </audio>




                        </div>



                

                <img className="abga" src={store.getState().inputValue.al.picUrl} alt=""/>
            </div>
        );
    }
}

export default withRouter(AudioDetail);